<template>
    <div class="header">
      <div>
        <div class="box1">
          <video
            id="videoCamera"
            class="canvas"
            :width="videoWidth"
            :height="videoHeight"
            autoPlay
          ></video>
          <canvas
            id="canvasCamera"
            class="canvas"
            :width="canvasWidth"
            :height="canvasHeight"
          ></canvas>
        </div>
      </div>
        <div class="main">
          <!--
            <div class="title" @click="goIndex">星星学苑</div>
            <div class="title" @click="goIndex">首页</div>
            <div class="title" @click="goMath">数字大战</div>
            <div class="title" @click="goEg">字母世界</div>
            <div class="title" @click="goCn">华夏传奇</div>
            <div class="title" @click="goMyStudy">我的成长</div>
          -->
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <form @click="goIndex">
              <span></span>
            <span></span>
            <span></span>
            <span></span>星星学苑</form>  
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;         
            <form @click="goIndex">
              <span></span>
            <span></span>
            <span></span>
            <span></span>学苑首页</form>
            <form @click="goMath">
              <span></span>
            <span></span>
            <span></span>
            <span></span>世界之旅</form>
            <form @click="goEg">
              <span></span>
            <span></span>
            <span></span>
            <span></span>字母星球</form>
            <form @click="goCn">
              <span></span>
            <span></span>
            <span></span>
            <span></span>华夏传奇</form>
            <form @click="goMyStudy">
              <span></span>
            <span></span>
            <span></span>
            <span></span>我的成长</form>
          
            <div class="user" @click="showMenu=!showMenu">
                <template v-if="user._id">
                    <div>{{user.username}}</div>
                    <span>{{user.username}}</span>
                </template>
                <template v-else>
                    <div></div>
                    <span>未登录</span>
                </template>
                <img src="../static/icons/down.png" />
            </div>
            <div class="menu" v-if="showMenu">
                <div class="menu-item" @click="userAction">{{user._id?'退出登录':'登录'}}</div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
  name: 'Header',
  data () {
    return {
      showMenu: false,
      os: false, //控制摄像头开关
      thisVideo: null,
      thisContext: null,
      thisCancas: null,
      imgSrc: "",
      videoWidth: 500,
      videoHeight: 400,
      canvasWidth:500,
      canvasHeight:400
    }
  },
  computed: {
    user () {
      return this.$store.state.user
    }
  },
  methods: {
    goEg () {
      if(this.global.sendfocus === 0){
        if(this.global.sendcamera === 0){
          console.log('global.sendfocus==0 sendcamera==0')
          return this.$route.path === '/eghome' || this.$router.replace('/eghome')
        }else{
          console.log('global.sendfocus==0')
          clearInterval(this.global.sendcamera);
          this.stopCamera()
          this.global.sendcamera = 0
          return this.$route.path === '/eghome' || this.$router.replace('/eghome')
        }
      }else{
        clearInterval(this.global.sendfocus);
        this.global.sendfocus = 0
        if(this.global.sendcamera === 0){
          console.log('global.sendcamera==0')
          return this.$route.path === '/eghome' || this.$router.replace('/eghome')
        }else{
          console.log('global.sendfocus sendcamera')
          clearInterval(this.global.sendcamera);
          this.stopCamera()
          this.global.sendcamera = 0
          return this.$route.path === '/eghome' || this.$router.replace('/eghome')
        }
      }
      // if not home page then go home
      return this.$route.path === '/eghome' || this.$router.replace('/eghome')
    },
    goIndex () {
      if(this.global.sendfocus === 0){
        if(this.global.sendcamera === 0){
          console.log('global.sendfocus==0 sendcamera==0')
          return this.$route.path === '/index' || this.$router.replace('/index')
        }else{
          console.log('global.sendfocus==0')
          clearInterval(this.global.sendcamera);
          this.stopCamera()
          this.global.sendcamera = 0
          return this.$route.path === '/index' || this.$router.replace('/index')
        }
      }else{
        clearInterval(this.global.sendfocus);
        this.global.sendfocus = 0
        if(this.global.sendcamera === 0){
          console.log('global.sendcamera==0')
          return this.$route.path === '/index' || this.$router.replace('/index')
        }else{
          console.log('global.sendfocus sendcamera')
          clearInterval(this.global.sendcamera);
          this.stopCamera()
          this.global.sendcamera = 0
          return this.$route.path === '/index' || this.$router.replace('/index')
        }
      }
    },
    goMath () {
      if(this.global.sendfocus === 0){
        if(this.global.sendcamera === 0){
          console.log('global.sendfocus==0 sendcamera==0')
          return this.$route.path === '/mathhome' || this.$router.replace('/mathhome')
        }else{
          console.log('global.sendfocus==0')
          clearInterval(this.global.sendcamera);
          this.stopCamera()
          this.global.sendcamera = 0
          return this.$route.path === '/mathhome' || this.$router.replace('/mathhome')
        }
      }else{
        clearInterval(this.global.sendfocus);
        this.global.sendfocus = 0
        if(this.global.sendcamera === 0){
          console.log('global.sendcamera==0')
          return this.$route.path === '/mathhome' || this.$router.replace('/mathhome')
        }else{
          console.log('global.sendfocus sendcamera')
          clearInterval(this.global.sendcamera);
          this.stopCamera()
          this.global.sendcamera = 0
          return this.$route.path === '/mathhome' || this.$router.replace('/mathhome')
        }
      }
    },
    goCn () {
      if(this.global.sendfocus === 0){
        if(this.global.sendcamera === 0){
          console.log('global.sendfocus==0 sendcamera==0')
          return this.$route.path === '/cnhome' || this.$router.replace('/cnhome')
        }else{
          console.log('global.sendfocus==0')
          clearInterval(this.global.sendcamera);
          this.stopCamera()
          this.global.sendcamera = 0
          return this.$route.path === '/cnhome' || this.$router.replace('/cnhome')
        }
      }else{
        clearInterval(this.global.sendfocus);
        this.global.sendfocus = 0
        if(this.global.sendcamera === 0){
          console.log('global.sendcamera==0')
          return this.$route.path === '/cnhome' || this.$router.replace('/cnhome')
        }else{
          console.log('global.sendfocus sendcamera')
          clearInterval(this.global.sendcamera);
          this.stopCamera()
          this.global.sendcamera = 0
          return this.$route.path === '/cnhome' || this.$router.replace('/cnhome')
        }
      }
    },
    goMyStudy () {
      if(this.global.sendfocus === 0){
        if(this.global.sendcamera === 0){
          console.log('global.sendfocus==0 sendcamera==0')
          return this.$route.path === '/mystudy' || this.$router.replace('/mystudy')
        }else{
          console.log('global.sendfocus==0')
          clearInterval(this.global.sendcamera);
          this.stopCamera()
          this.global.sendcamera = 0
          return this.$route.path === '/mystudy' || this.$router.replace('/mystudy')
        }
      }else{
        clearInterval(this.global.sendfocus);
        this.global.sendfocus = 0
        if(this.global.sendcamera === 0){
          console.log('global.sendcamera==0')
          return this.$route.path === '/mystudy' || this.$router.replace('/mystudy')
        }else{
          console.log('global.sendfocus sendcamera')
          clearInterval(this.global.sendcamera);
          this.stopCamera()
          this.global.sendcamera = 0
          return this.$route.path === '/mystudy' || this.$router.replace('/mystudy')
        }
      }
    },
    userAction () {
      if(this.global.sendfocus === 0){
        if(this.global.sendcamera === 0){
          console.log('global.sendfocus==0 sendcamera==0')
          if (this.user._id) {
            if (confirm('确认退出登录？')) {
              this.$store.commit('logout')
              this.showMenu = false
              return this.$route.path === '/index' || this.$router.replace('/index')
            }
          } else {
            this.$event.emit('login')
            this.showMenu = false
          }
        }else{
          console.log('global.sendfocus==0')
          clearInterval(this.global.sendcamera);
          this.stopCamera()
          this.global.sendcamera = 0
          if (this.user._id) {
            if (confirm('确认退出登录？')) {
              this.$store.commit('logout')
              this.showMenu = false
              return this.$route.path === '/index' || this.$router.replace('/index')
            }
          } else {
            this.$event.emit('login')
            this.showMenu = false
          }
        }
      }else{
        clearInterval(this.global.sendfocus);
        this.global.sendfocus = 0
        if(this.global.sendcamera === 0){
          console.log('global.sendcamera==0')
          if (this.user._id) {
            if (confirm('确认退出登录？')) {
              this.$store.commit('logout')
              this.showMenu = false
              return this.$route.path === '/index' || this.$router.replace('/index')
            }
          } else {
            this.$event.emit('login')
            this.showMenu = false
          }
        }else{
          console.log('global.sendfocus sendcamera')
          clearInterval(this.global.sendcamera);
          this.stopCamera()
          this.global.sendcamera = 0
          if (this.user._id) {
            if (confirm('确认退出登录？')) {
              this.$store.commit('logout')
              this.showMenu = false
              return this.$route.path === '/index' || this.$router.replace('/index')
            }
          } else {
            this.$event.emit('login')
            this.showMenu = false
          }
        }
      }
    },
    ongoing(){
      console.log('摄像头ongoing')
      this.photographBtn();
      this.submitBtn();
    },
    submitBtn() {
      console.log('Into submitBtn');
      var dataToSend = {
          'imgData': this.imgSrc
      };
      var url = this.global.ip
      this.$http.post(url +'/api/img', dataToSend).then(res => {
          var focus = JSON.parse(JSON.stringify(res.data))
          console.log((focus.focus));
          if (focus.focus===1) {
            this.global.unfocus += 1
          }else{
            this.global.focus += 1
          }
      });
    },
    openCamera() {
      console.log('Into openCamera')
      this.$nextTick(() => {
        const _this = this;
        this.os = false;
        this.thisCancas = document.getElementById("canvasCamera");
        this.thisContext = this.thisCancas.getContext("2d");
        this.thisVideo = document.getElementById("videoCamera");
        if (navigator.mediaDevices === undefined) {
          navigator.mediaDevices = {};
        }
        if (navigator.mediaDevices.getUserMedia === undefined) {
          navigator.mediaDevices.getUserMedia = function (constraints) {
            let getUserMedia =
              navigator.webkitGetUserMedia ||
              navigator.mozGetUserMedia ||
              navigator.getUserMedia;
            if (!getUserMedia) {
              return Promise.reject(
                new Error("getUserMedia is not implemented in this browser")
              );
            }
            return new Promise(function (resolve, reject) {
              getUserMedia.call(navigator, constraints, resolve, reject);
            });
          };
        }
        const constraints = {
          audio: false,
          video: {
            width: _this.videoWidth,
            height: _this.videoHeight,
            transform: "scaleX(-1)",
          },
        };
        console.log('aboutTo navigator.mediaDevices')
        navigator.mediaDevices.getUserMedia(constraints)
          .then(function (stream) {
            if ("srcObject" in _this.thisVideo) {
              console.log('in _this.thisVideo')
              _this.thisVideo.srcObject = stream;
            } else {
              _this.thisVideo.src = window.URL.createObjectURL(stream);
            }
            _this.thisVideo.onloadedmetadata = function () {
              _this.thisVideo.play();
            };
          })
          .catch((err) => {
            console.log(err);
            this.$message({
              message: "没有开启摄像头权限或浏览器版本不兼容",
              type: "warning",
            });
          });
      });
    },
    photographBtn() {
      // 点击，canvas画图
      this.thisContext.drawImage(
        this.thisVideo,
        0,
        0,
        this.videoWidth,
        this.videoHeight
      );
      // 获取图片base64链接 >>> 这里是base64格式的图片
      this.imgSrc = this.thisCancas.toDataURL("image/png");
    },
    //清空画布
    clearCanvas(id) {
      let c = document.getElementById(id);
      let cxt = c.getContext("2d");
      cxt.clearRect(0, 0, c.width, c.height);
    },
    //重置画布
    resetBtn() {
      this.imgSrc = "";
      this.clearCanvas("canvasCamera");
    },
    //关闭摄像头
    stopCamera() {
      if (this.thisVideo && this.thisVideo !== null) {
        this.thisVideo.srcObject.getTracks()[0].stop();
      }
    },
    downloadFile(fileName, content) {
        let aLink = document.createElement('a');
        let blob = this.base64ToBlob(content); //new Blob([content]);
        aLink.download = fileName;
        aLink.href = URL.createObjectURL(blob);
        aLink.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));//兼容火狐
    }, 
    base64ToBlob(code) {
        let contentType = code.split(':')[1];
        let raw = window.atob(code);
        let rawLength = raw.length;
        let uInt8Array = new Uint8Array(rawLength);
        for (let i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], { type: contentType });
    },
    downloadpic(){
      this.downloadFile("/hi.png",this.imgSrc)
    },
  }
}
</script>

<style scoped>
#canvasCamera{
  margin-left: 20px;
}
.box1{
  background:rgba(249,93,62,0.1)
}
.canvas {
  display: none;/* xujiawei是大神*/
}
.header {
  position: absolute;
  top: 0;
  width: 100%;
  background: #40BC96;
  height: 80px;
  z-index: 1;
}

.main {
  position: relative;
  max-width: 1300px;
  margin: 0 auto;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.title {
  height:80px;
  width:185px;
  line-height: 80px;
  text-align: center;
  font-size: 32px;
  font-weight: bolder;
  cursor: pointer;
  color: #FFFFFF;
  padding: 0 10px;
  box-sizing: border-box;
  font-family: Calibri, sans-serif;
  z-index: 10;
}
.title:hover {
background: #F9CC28;
color: #455358;
}

.user {
  height: 100%;
  display: flex;
  align-items: center;
  padding-right: 10px;
  cursor: pointer;
}

.user div {
  height: 32px;
  width: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  overflow: hidden;
  padding: 2px;
  box-sizing: border-box;
  font-size: 12px;
  letter-spacing: 0.5px;
  font-weight: 600;
  background: #248491;
  color: #FFFFFF;
  box-shadow: 0 0 4px 0 rgba(0, 0, 0, .24);
}

.user span {
  font-size: 13px;
  color: #FFFFFF;
  font-weight: 600;
  margin-left: 10px;
}

.user img {
  margin-left: 8px;
  width: 15px;
  height: 15px;
}

.menu {
  position: absolute;
  width: 180px;
  right: 0;
  top: 80px;
  box-shadow: -2px -2px 6px -2px rgba(0, 0, 0, .12);
  animation: blur 0.5s;
  animation-fill-mode: both;
}

@keyframes blur {
  0%   { opacity: 0 }
  100% { opacity: 1 }
}

.menu-item {
  position: absolute;
  background: #FFFFFF;
  width: 100%;
  height: 40px;
  cursor: pointer;
  color: #2d3639;
  display: flex;
  align-items: center;
  padding-left: 15px;
  box-sizing: border-box;
  font-size: 15px;
  font-weight: 600;
  transition: all 0.4s ease;
  z-index: 11;
}

.menu-item:hover {
  background: #F9CC28;
}

.menu:after {
  background: #FFFFFF;
  content: '';
  position: absolute;
  right: 3px;
  top: -7px;
  transform: rotate(45deg);
  height: 15px;
  width: 15px;
  z-index: 10;
}


.header .main form {
    position: relative;
    display: inline-block;
    padding: 10px 20px;
    color: #f1f4f4;
    font-size: 26px;
    font-weight: 600;
    text-decoration: none;
    text-transform: uppercase;
    overflow: hidden;
    transition: .5s;
    margin-top: 5px;
    margin-right: 35px;
    letter-spacing: 4px
  }
  
  .header .main form:hover {
    background: #2aedaf;
    color: #fafcfc;
    border-radius: 5px;
    box-shadow: 0 0 5px #2aedaf,
    0 0 25px #2aedaf,
    0 0 50px #2aedaf,
    0 0 100px #2aedaf;
  }

  .header .main form span {
    position: absolute;
    display: block;
  }
  
  .header .main form span:nth-child(1) {
    top: 0;
    left: -100%;
    width: 100%;
    height: 2px;
    background: linear-gradient(90deg, transparent, #03e9f4);
    animation: btn-anim1 1s linear infinite;
  }
  
  @keyframes btn-anim1 {
    0% {
      left: -100%;
    }
    50%, 100% {
      left: 100%;
    }
  }
  
  .header .main form span:nth-child(2) {
    top: -100%;
    right: 0;
    width: 2px;
    height: 100%;
    background: linear-gradient(180deg, transparent, #03e9f4);
    animation: btn-anim2 1s linear infinite;
    animation-delay: .25s
  }
  
  @keyframes btn-anim2 {
    0% {
      top: -100%;
    }
    50%, 100% {
      top: 100%;
    }
  }
  
  .header .main form span:nth-child(3) {
    bottom: 0;
    right: -100%;
    width: 100%;
    height: 2px;
    background: linear-gradient(270deg, transparent, #03e9f4);
    animation: btn-anim3 1s linear infinite;
    animation-delay: .5s
  }
  
  @keyframes btn-anim3 {
    0% {
      right: -100%;
    }
    50%, 100% {
      right: 100%;
    }
  }
  
  .header .main form span:nth-child(4) {
    bottom: -100%;
    left: 0;
    width: 2px;
    height: 100%;
    background: linear-gradient(360deg, transparent, #03e9f4);
    animation: btn-anim4 1s linear infinite;
    animation-delay: .75s
  }
  
  @keyframes btn-anim4 {
    0% {
      bottom: -100%;
    }
    50%, 100% {
      bottom: 100%;
    }
  }
</style>
